<template>
  <BreadcrumbBar
    parent-label="Authority Management"
    child-label="Permission Management"
  ></BreadcrumbBar>

  <InputForm>
    <InputItem label="条件查询权限" more-long="500">
      <el-cascader
        style="width: 100%"
        v-model="queryPermissionSortId"
        :options="sortTree"
        :props="{ checkStrictly: true }"
        clearable
        placeholder="请选择上级分类（可选）"
        @visible-change="selectVisibleChangeHandler"
        size="large"
      />
    </InputItem>

    <ButtomItem label="操作">
      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="getPermissionsList"
      >
        查询
      </el-button>

      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="openCreatePermissionDialog"
      >
        新建权限
      </el-button>
    </ButtomItem>
  </InputForm>

  <!-- 权限表格 -->
  <TableCard
    operationBarLabel="批量操作权限"
    :show-expand="50"
    :table-max-height="450"
  >
    <template #operationBar>
      <el-button
        v-once-click
        color="#626aef"
        plain
        size="small"
        @click="updatePermissionsStatus(multipleSelectionItems, 0)"
      >
        启用
      </el-button>
      <el-button
        v-once-click
        type="info"
        size="small"
        @click="updatePermissionsStatus(multipleSelectionItems, 1)"
      >
        禁用
      </el-button>
      <el-popconfirm
        title="确认删除"
        placement="right"
        @confirm="deletePermissions(multipleSelectionItems)"
      >
        <template #reference>
          <el-button v-once-click color="#F56C6C" plain size="small">
            删除
          </el-button>
        </template>
      </el-popconfirm>
    </template>

    <template #table="{ maxHeight }">
      <el-table
        :data="querPermissionList"
        stripe
        style="width: 100%"
        :max-height="maxHeight"
        @selection-change="handleSelectionChange"
        :headerCellStyle="tableHeaderCellStyle"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column property="enable" label="Enable" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.enable === 1" type="danger"> 禁用 </el-tag>
            <el-tag v-if="scope.row.enable === 0" type="success"> 启用 </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="name" label="Name" width="140" />
        <el-table-column property="code" label="Code" sortable width="260" />
        <el-table-column
          property="description"
          label="Description"
          min-width="360"
          show-overflow-tooltip
        />
        <el-table-column label="Sort" width="360" show-overflow-tooltip>
          <template #default="scope">
            {{
              getDescriptionStr(findParentValues(sortTree, scope.row?.sortId))
            }}
          </template>
        </el-table-column>
        <el-table-column
          property="createTime"
          label="CreateTime"
          sortable
          width="190"
        />
        <el-table-column
          property="updateTime"
          label="UpdateTime"
          sortable
          width="190"
        />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              v-once-click
              type="info"
              size="small"
              v-if="scope.row.enable === 0"
              @click="updatePermissionsStatus([scope.row.id], 1)"
            >
              禁用
            </el-button>
            <el-button
              v-once-click
              color="#626aef"
              plain
              size="small"
              v-if="scope.row.enable === 1"
              @click="updatePermissionsStatus([scope.row.id], 0)"
            >
              启用
            </el-button>
            <el-button
              v-once-click
              color="#E6A23C"
              plain
              size="small"
              @click="
                openUpdatePermissionDialog(
                  scope.row.id,
                  scope.row.name,
                  scope.row.code,
                  scope.row.description,
                  scope.row.sortId
                )
              "
            >
              修改
            </el-button>
            <el-popconfirm
              title="确认删除"
              placement="left"
              @confirm="deletePermissions([scope.row.id])"
            >
              <template #reference>
                <el-button v-once-click color="#F56C6C" plain size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template #paginationBar>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :background="true"
        :total="total"
        :page-sizes="[20, 30, 40, 50, 60]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageNumChange"
      />
    </template>
  </TableCard>

  <!--  -->
  <!-- 权限创建对话框 -->
  <el-dialog
    v-model="createPermissionDialogVisible"
    title="创建权限对话框"
    draggable
    width="800px"
    :before-close="closePermissionDialog"
  >
    <InputForm>
      <InputItem label="权限分类" more-long>
        <el-cascader
          style="width: 100%; height: 100%"
          v-model="tempPermissionSortId"
          :options="sortTree"
          :props="{ checkStrictly: true }"
          placeholder="请选择权限分类"
          @visible-change="selectVisibleChangeHandler"
          size="large"
      /></InputItem>
      <InputItem label="权限名称" more-long>
        <el-input
          v-model="permissionName"
          placeholder="请输入权限名称"
          clearable
          maxlength="20"
          show-word-limit
      /></InputItem>
      <InputItem label="权限编码" more-long>
        <el-input
          v-model="permissionCode"
          placeholder="输入权限编码(禁止中文)"
          clearable
          maxlength="50"
          show-word-limit
      /></InputItem>
      <InputItem label="权限描述" more-long>
        <el-input
          v-model="permissionDesc"
          placeholder="请输入权限描述"
          clearable
          maxlength="20"
          show-word-limit
      /></InputItem>
    </InputForm>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#909399"
          plain
          @click="closePermissionDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          color="#626aef"
          @click="createDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  -->
  <!-- 权限修改对话框 -->
  <el-dialog
    v-model="updatePermissionDialogVisible"
    title="修改权限对话框"
    draggable
    width="800px"
    :before-close="closePermissionDialog"
  >
    <InputForm>
      <InputItem label="权限分类" more-long>
        <el-cascader
          style="width: 100%; height: 100%"
          v-model="tempPermissionSortId"
          :options="sortTree"
          :props="{ checkStrictly: true }"
          placeholder="请选择权限分类"
          @visible-change="selectVisibleChangeHandler"
          size="large"
      /></InputItem>
      <InputItem label="权限名称" more-long>
        <el-input
          v-model="permissionName"
          placeholder="请输入权限名称"
          clearable
          maxlength="20"
          show-word-limit
      /></InputItem>
      <InputItem label="权限编码" more-long>
        <el-input
          v-model="permissionCode"
          placeholder="输入权限编码(禁止中文)"
          clearable
          maxlength="50"
          show-word-limit
      /></InputItem>
      <InputItem label="权限描述" more-long>
        <el-input
          v-model="permissionDesc"
          placeholder="请输入权限描述"
          clearable
          maxlength="20"
          show-word-limit
      /></InputItem>
    </InputForm>
    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#909399"
          plain
          @click="closePermissionDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          color="#626aef"
          @click="updateDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { storeToRefs } from 'pinia'
import { useSortTreeStore, useThemeStore } from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'
import {
  getPermissionsListApi,
  setPermissionApi,
  deletePermissionsApi,
  updatePermissionsStatusApi,
} from '@/request/api/permissions'

import InputForm from '@/components/InputForm/InputForm.vue'
import InputItem from '@/components/InputForm/InputItem.vue'
import ButtomItem from '@/components/InputForm/ButtomItem.vue'
import TableCard from '@/components/TableCard/TableCard.vue'
import BreadcrumbBar from '@/components/BreadcrumbBar/BreadcrumbBar.vue'

const { originData } = storeToRefs(useSortTreeStore())
const { getSortList, formattingSortData, findParentValues, getDescriptionStr } =
  useSortTreeStore()

const { tableHeaderCellStyle } = useThemeStore()
const { openAlert } = useMessageAlertStore()

onMounted(() => {
  getPermissionsList()
  selectVisibleChangeHandler(true)
})

// 经过筛选后的分类树形列表
const sortTree = ref<SortTreeItf[]>([])
// 下拉框显示回调函数
const selectVisibleChangeHandler = (visible: boolean) => {
  if (!visible) return
  if (originData.value.length === 0) getSortList()
  sortTree.value = formattingSortData(originData.value, null, 'permission')
}

const total = ref<number>(0)
const pageNum = ref<number>(1)
const pageSize = ref<number>(20)
const handlePageNumChange = (val: number) => {
  pageNum.value = val
  getPermissionsList()
}
const handlePageSizeChange = (val: number) => {
  pageSize.value = val
  getPermissionsList()
}

// 权限分类id，包含所有上级分类id
const queryPermissionSortId = ref<string[]>([])
// 查询到的权限列表
const querPermissionList = ref<PermissionItf[]>([])
// 获取权限列表
const getPermissionsList = async () => {
  let sortId = ''
  const q = queryPermissionSortId.value
  if (q && q.length > 0) sortId = q[q.length - 1]

  const res = await getPermissionsListApi(pageNum.value, pageSize.value, sortId)
  if (res.code !== 200) return openAlert.error(res.message)
  // ElMessage.success('查询权限成功')
  querPermissionList.value = res.data.records
  total.value = res.data.total
}

// 当前权限id
const currentPermissionId = ref<string>('')
// 权限名称
const permissionName = ref<string>('')
// 权限信息
const permissionCode = ref<string>('')
// 权限描述
const permissionDesc = ref<string>('')
// 创建，修改权限时的分类id
const tempPermissionSortId = ref<string[]>([])

// 创建权限对话框
const createPermissionDialogVisible = ref(false)
// 修改权限对话框
const updatePermissionDialogVisible = ref(false)

const openCreatePermissionDialog = () => {
  createPermissionDialogVisible.value = true
}
const openUpdatePermissionDialog = (
  id: string,
  name: string,
  code: string,
  desc: string,
  sortId: string
) => {
  currentPermissionId.value = id
  permissionName.value = name
  permissionCode.value = code
  permissionDesc.value = desc
  tempPermissionSortId.value = findParentValues(sortTree.value, sortId)
  updatePermissionDialogVisible.value = true
}
const closePermissionDialog = () => {
  createPermissionDialogVisible.value = false
  updatePermissionDialogVisible.value = false
  permissionName.value = ''
  permissionCode.value = ''
  permissionDesc.value = ''
  currentPermissionId.value = ''
  tempPermissionSortId.value = []
}
const createDialogConfirmHandler = () => {
  createPermission()
  closePermissionDialog()
}
const updateDialogConfirmHandler = () => {
  updatePermission()
  closePermissionDialog()
}

// 创建权限
const createPermission = async () => {
  let sortId = ''
  const t = tempPermissionSortId.value
  if (t && t.length > 0) sortId = t[t.length - 1]

  const res = await setPermissionApi({
    name: permissionName.value,
    code: permissionCode.value,
    description: permissionDesc.value,
    sortId: sortId,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('权限创建成功！')
  getPermissionsList()
}

// 修改权限信息
const updatePermission = async () => {
  let sortId = ''
  const t = tempPermissionSortId.value
  if (t && t.length > 0) sortId = t[t.length - 1]

  const res = await setPermissionApi({
    name: permissionName.value,
    code: permissionCode.value,
    description: permissionDesc.value,
    sortId: sortId,
    id: currentPermissionId.value,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('权限修改成功！')
  getPermissionsList()
}

// 多选权限选项
const multipleSelectionItems = ref<string[]>([])
const handleSelectionChange = (val: PermissionItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleSelectionItems.value = ids
}

// 批量删除权限
const deletePermissions = async (ids: string[]) => {
  const res = await deletePermissionsApi(ids)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('权限删除成功！')
  getPermissionsList()
}

// 批量更新权限状态
const updatePermissionsStatus = async (ids: string[], status: 0 | 1) => {
  const res = await updatePermissionsStatusApi(ids, status)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('权限状态更新成功！')
  getPermissionsList()
}
</script>

<style lang="less" scoped></style>
